﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngineInternal;
using System;

public class SceneController : MonoBehaviour
{
	static public GameObject m_TopLeftMenu = null;
	static public GameObject m_TopRightMenu = null;

	static public SceneController s_Sc = null;
    static public SceneController SC
    {
        get {
            if (s_Sc == null)            
                Create();
            return s_Sc; 
        }
        set { }
    }

    public Scene m_SceneScript = null;
    static public Scene CrrSceneScript
    {
        get { return SC.m_SceneScript; }
        set { SC.m_SceneScript = value; }
    }

    string m_CrrSceneName = null;
	static public string CrrScene
	{
		get { return SC.m_CrrSceneName; }
		set { }
	}

	
	string m_PreSceneName = "";
	string m_NextScene = "";
	bool isNeedSceneChange = false;
	bool isSceneLoadIngProcess = false;

	public static void Create()
	{
        if (s_Sc == null)
		{
			GameObject temp = new GameObject("SceneController");
            s_Sc = temp.AddComponent("SceneController") as SceneController;
			GameObject.DontDestroyOnLoad(temp);
			PawnManifest.LoadTakeInAdvance();
		}
	}

	void UpdateTimes()      // 각종 로컬 타임 관리
	{
		// ex) life += Time.deltaTime;
	}


	void Update()
	{
		UpdateTimes();
	}

	void FixedUpdate()  // 씬 변경 동기화
	{
		//if (isNeedSceneChange)
		//{
		//	LoadLevelProcess(m_NextScene);
		//	isNeedSceneChange = false;
		//}
	}

	public string GetPreScene()
	{
		return m_PreSceneName;
	}

	public void SetLoadingActive(bool isActive)
	{
		StartCoroutine(CoSetLoadingActive(isActive));
	}


	public IEnumerator CoSetLoadingActive(bool isActive)            // 엑티비티 설정
	{
        RecieaveInputObject.IsAbleControl = !isActive;

        yield return new WaitForEndOfFrame();     

		if (isActive)
		{
#if UNITY_IPHONE
            Handheld.SetActivityIndicatorStyle(iOSActivityIndicatorStyle.White);
#elif UNITY_ANDROID
			Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Small);
#endif			
            Handheld.StartActivityIndicator();
		}
		else
		{
//#if !UNITY_EDITOR
			Handheld.StopActivityIndicator();
//#endif
        }		
	}


	IEnumerator LoadLevelWithFadeOut(string scene , float delay)
	{
        SoundController.PlaySound("UI_screen_change");
		
        SC.SetLoadingActive(true);

        if (CrrSceneScript != null && CrrSceneScript.isHaveFadeOut)
        {
            FadeScreen.PlayNGUIFadeOut();

            yield return new WaitForSeconds(delay + FadeScreen.GetDuration());
            

            SC.HideLeftTopMenu();
            SC.HideTopRightMenu();
        }
        else
			yield return new WaitForSeconds(delay);
		
		Popup_Blur.ClearAll(); // 팝업에서 Blur 효과 강제 제거
		//SoundController.PlaySound("UI_screen_change");

		LoadLevelProcess(scene);
		isNeedSceneChange = false;
	}


	public static void LoadLevel(string scene ,float delay = 0.1f)
	{
        if (SC == null)
        {
            Create();
        }

        Time.timeScale = 1;     //타임스케일 1로 변경

		//터치 안받게 처리하는 부분
		//RecieaveInputObject.isAbleControl = false;

		foreach (Camera tCam in Camera.allCameras)
		{
			UICamera uiCam = tCam.GetComponent<UICamera>();
            if (uiCam != null  && !uiCam.name.Equals("PopupCamera") && !uiCam.name.Equals("ToastCamera"))
			{
				uiCam.eventReceiverMask = 0;
			}
		}
		//------------------------------------------------

		SC.StartCoroutine(SC.LoadLevelWithFadeOut(scene, delay));
	}

	public IEnumerator LoadLevel_Async(string scene)
	{
		if( CrrSceneScript )
			CrrSceneScript.OnWillDestroy();
		yield return Application.LoadLevelAsync(scene);
	}


	void LoadLevelProcess(string scene)
	{
		string scenePrefabPath = scene;

		if( CrrSceneScript != null)
			CrrSceneScript.OnWillDestroy();

		if( scene != m_CrrSceneName ) //같은씬은 이전 씬으로 취급하지 않음
			m_PreSceneName = m_CrrSceneName;

		m_CrrSceneName = scene;
		
		//ClearMemory();
		Application.LoadLevel(scenePrefabPath);
	}


	public static void LoadPreLevel()
	{
		LoadLevel(SC.m_PreSceneName);
	}


	void OnApplicationFocus(bool focus)
	{
	}


	public static void SetAllChildsLayer(Transform t_trans, int layer)
	{
		t_trans.gameObject.layer = layer;

		for (int i = 0; i < t_trans.childCount; i++)
		{
			SetAllChildsLayer(t_trans.GetChild(i), layer);
		}
	}

    //public static void ClearMemory(bool wait_collect = true)
    //{
    //    //AssetBundleManager.UnLoadBundle(false);

    //    Resources.UnloadUnusedAssets();

    //    GC.Collect();

    //    if (wait_collect)
    //    {
    //        GC.WaitForPendingFinalizers();
    //    }	
	//}

	#region 좌측 상단 메뉴
	void HideLeftTopMenu()
	{
		if (m_TopLeftMenu == null)
			return;

		m_TopLeftMenu.transform.parent = null;
		m_TopLeftMenu.SetActive(false);
	}

	static public void ShowTopLeftMenu()
	{
		if (SceneController.m_TopLeftMenu == null)
		{
			GameObject topLeftObject = Instantiate(ResourceLoader.Load("Prefab/Common/Panel - TopLeft"), Vector3.zero, Quaternion.identity) as GameObject;
			SceneController.m_TopLeftMenu = topLeftObject;
			SceneController.m_TopLeftMenu.name = "Panel - TopLeft";
			GameObject.DontDestroyOnLoad(SceneController.m_TopLeftMenu);
			SceneController.m_TopLeftMenu.SetActive(false);
		}

		SceneController.m_TopLeftMenu.GetComponent<AnimatedAlpha>().alpha = 1.0f;
		SceneController.m_TopLeftMenu.transform.parent = GameObject.Find("UI Root").transform;
		SceneController.m_TopLeftMenu.transform.localPosition = Vector3.zero;
		SceneController.m_TopLeftMenu.transform.localScale = Vector3.one;
		SceneController.m_TopLeftMenu.SetActive(true);
		SceneController.m_TopLeftMenu.GetComponent<Panel_TopLeft>().UpdateUserName();

	}
	#endregion

	#region 뒤로가기 버튼
	void HideTopRightMenu()
	{
		if (m_TopRightMenu == null)
			return;

		m_TopRightMenu.GetComponent<Panel_TopRight>().helpButton.SetActive(false);
		m_TopRightMenu.transform.parent = null;
		m_TopRightMenu.SetActive(false);
	}

	static public void ShowTopRightMenu()
	{
		if (SceneController.m_TopRightMenu == null)
		{
			GameObject topRightObject = Instantiate(ResourceLoader.Load("Prefab/Common/Panel - TopRight"), Vector3.zero, Quaternion.identity) as GameObject;
			SceneController.m_TopRightMenu = topRightObject;
			SceneController.m_TopRightMenu.name = "Panel - TopRight";
			GameObject.DontDestroyOnLoad(SceneController.m_TopRightMenu);
			SceneController.m_TopRightMenu.SetActive(false);
		}

		SceneController.m_TopRightMenu.transform.parent = GameObject.Find("UI Root").transform;
		SceneController.m_TopRightMenu.transform.localPosition = Vector3.zero;
		SceneController.m_TopRightMenu.transform.localScale = Vector3.one;
		SceneController.m_TopRightMenu.SetActive(true);
	}
	#endregion

	public static string GetCurrentBattleSceneName(int areaId)
	{
		switch (areaId)
		{
			case 100:
				return "Battle_4vs4_Forest_Poeta_01";
				break;
			case 101:
				return "Battle_4vs4_Heights_Verteron_01";
				break;
			case 102:
				return "Battle_4vs4_Wasteland_Theobomos_01";
				break;
		}

		return "Battle_4vs4_Forest_Poeta_01";
	}
   
    public static string GetCurrentBattleResultPosName(int areaId)
    {
        switch (areaId)
        {
            case 100:
				return "Result_PCPos_4vs4_Poeta_01";
                break;
            case 101:
				return "Result_PCPos_4vs4_Verteron_01";
                break;
            case 102:
				return "Result_PCPos_4vs4_Theobomos_01";
                break;
        }

        return "Result_PCPos_4vs4_Poeta_01";
    }

	public static int GetAreaIDFromSceneName(string _sceneName)
	{
		switch (_sceneName)
		{
			case "Battle_4vs4_Forest_Poeta_01":
				return 100;
				break;
			case "Battle_4vs4_Heights_Verteron_01":
				return 101;
				break;
			case "Battle_4vs4_Wasteland_Theobomos_01":
				return 102;
				break;
		}
		
		return 100;
	}

    public void LocalizeChange()
    {       
        GameObject[] gos = (GameObject[])GameObject.FindObjectsOfType(typeof(GameObject));
        //foreach (GameObject go in gos)
        //{
        //    if (go && go.transform.parent == null)
        //    {
        //        go.gameObject.BroadcastMessage("OnLanguageChange", SendMessageOptions.DontRequireReceiver);
        //    }
        //} 

        foreach (GameObject go in gos)
        {
            go.SendMessage("OnLanguageChange", SendMessageOptions.DontRequireReceiver);           
        } 
    }
}
